﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System.Windows.Forms;
using System.Windows.Threading;
using Microsoft.WindowsAPICodePack.Shell;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;


//[assembly:SuppressIldasm()]
namespace MyMediaPlayer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        List<string> files = new List<string>();
        DispatcherTimer tmrPosition = new DispatcherTimer();
        string[] supportedFormat = { ".mp4", ".mp3", ".asf", ".3gp", ".3g2" };
        ClipBoardHelper cbh;
        public MainWindow()
        {
            cbh = new ClipBoardHelper();
            if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
            {
                string[] args = Environment.GetCommandLineArgs();
                if (args.Length > 1)
                {
                    List<string> lstSupFiles = new List<string>();
                    foreach (string arg in args)
                        if (supportedFormat.Contains(System.IO.Path.GetExtension(arg)))
                            lstSupFiles.Add(arg);
                    cbh.Send(lstSupFiles.ToArray());
                }
                System.Windows.Application.Current.Shutdown(0);
            }
            cbh.ClipBoardChanged += (sender, ce) =>
            {
                foreach (string item in ce.Files)
                {
                    this.files.Add(item);
                }
            };
            InitializeComponent();
        }
        bool isPlaying;

        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {

            if (isPlaying)//isJustRun == true
            {
                player.Pause();
                isPlaying = false;
                tmrPosition.IsEnabled = false;
                imgBtnPlay.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.control.png"));
                btnBackward.IsEnabled = false;
                btnPrevouis.IsEnabled = false;
                btnForward.IsEnabled = false;
                btnNext.IsEnabled = false;
            }
            else if (player.Source != null)
            {


                if (player.Position == player.NaturalDuration.TimeSpan)
                {
                    player.Position = new TimeSpan(0, 0, 0);
                }
                player.Play();
                isPlaying = true;
                tmrPosition.IsEnabled = true;
                imgBtnPlay.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.control.Puse.png"));
                btnBackward.IsEnabled = true;
                btnPrevouis.IsEnabled = true;
                btnForward.IsEnabled = true;
                btnNext.IsEnabled = true;
                btnStop.IsEnabled = true;
            }
            else if (this.files.Count > 0)
            {
                try
                {
                    player.Source = new Uri(this.files[fileIndex]);
                    player.Play();
                    imgBtnPlay.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.control.Puse.png"));
                    tmrPosition.IsEnabled = true;
                    isPlaying = true;
                    btnBackward.IsEnabled = true;
                    btnPrevouis.IsEnabled = true;
                    btnForward.IsEnabled = true;
                    btnNext.IsEnabled = true;
                    btnStop.IsEnabled = true;
                    btnPlay.IsEnabled = true;
                    //this.Width = this.player.ActualWidth;
                    //this.Height = this.player.ActualHeight;
                    //                    System.Windows.Application.Current.MainWindow.SizeToContent = 
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }

            }
            else return;

        }



        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog() { Multiselect = true, FileName = "", Filter = "All File|*.*|MP4 Files|*.mp4|MP3 Files|*.mp3|ASF Files|*.asf|3G2|*.3g2|3GP|*.3gp" };
            if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.files.AddRange(op.FileNames);//.ToList<string>();
                if (!isPlaying)
                {
                    this.fileIndex = 0;
                    btnPlay.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
                }

            }
        }

        private void GeneratList()
        {
            stcList.Children.Clear();
            int count = 1;
            foreach (string item in files)
            {


                // Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="30,0,0,0"
                //Width = stcList.ActualWidth - 10,
                StackPanel stc = new StackPanel() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(5, 3, 0, 0), Orientation = System.Windows.Controls.Orientation.Horizontal, Background = (Brush)System.Windows.Application.Current.Resources["AccentColorBrush"], Opacity = 1.5 };

                //Shadow
                //DropShadowBitmapEffect dr = new DropShadowBitmapEffect() { Direction = 300, Color = ((SolidColorBrush)System.Windows.Application.Current.Resources["AccentColorBrush"]).Color , ShadowDepth = 5,Softness = 0.1,Opacity = 0.9};
                DropShadowEffect dr = new DropShadowEffect() { Direction = 300, Color = ((SolidColorBrush)System.Windows.Application.Current.Resources["AccentColorBrush"]).Color, ShadowDepth = 6, BlurRadius = 3, Opacity = 0.5 };//((SolidColorBrush)System.Windows.Application.Current.Resources["AccentColorBrush"]).Color

                Border bd = new Border() { BorderBrush = (Brush)System.Windows.Application.Current.Resources["AccentColorBrush"], BorderThickness = new Thickness(0), Effect = dr, };
                bd.Child = stc;
                //Animation
                DoubleAnimation da = new DoubleAnimation(0.5, 1, new Duration(TimeSpan.FromSeconds(1))) { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
                ScaleTransform sc = new ScaleTransform(0.8, 0.8);
                ScaleTransform sc1 = new ScaleTransform(1, 1);
                stc.MouseEnter += (s, ee) => { stc.BeginAnimation(OpacityProperty, da); };
                stc.MouseLeave += (s, ee) => { stc.BeginAnimation(OpacityProperty, null); };
                stc.MouseDown += (s, ee) => { stc.LayoutTransform = sc; };


                //Thumnail
                Image img = new Image();
                img.Source = ShellFile.FromFilePath(item).Thumbnail.BitmapSource;
                img.Width = img.Height = img.MaxWidth = img.MaxHeight = 48;
                img.Margin = new Thickness(10, 0, 10, 0);

                //Label File N
                System.Windows.Controls.Label lbl = new System.Windows.Controls.Label();
                lbl.MaxWidth = 150;
                lbl.Foreground = Brushes.Snow;
                lbl.Margin = new Thickness(0, 0, 0, 10);
                string cont = count.ToString() + @"\ " + System.IO.Path.GetFileName(item);
                lbl.Content = cont.Substring(0, 15) + " ··· " + cont.Substring(cont.Length - 4);
                //lbl.Content = new TextBlock() { TextWrapping = TextWrapping.Wrap, Text = System.IO.Path.GetFileName(item) };

                stc.MouseUp += (s, ee) =>
                {
                    stc.LayoutTransform = sc1;
                };
                stc.MouseLeftButtonUp += (s, ee) =>
                {
                    if (fileIndex == Convert.ToInt32(lbl.Content.ToString().Split('\\')[0]) - 1)
                    {
                        return;
                    }
                    fileIndex = Convert.ToInt32(lbl.Content.ToString().Split('\\')[0]) - 1;
                    if (isPlaying)
                    {
                        player.Stop();
                        tmrPosition.IsEnabled = false;
                        isPlaying = false;
                    }
                    player.Source = new Uri(this.files[fileIndex]);
                    player.Play();
                    tmrPosition.IsEnabled = true;
                    isPlaying = true;
                };
                count++;

                stc.Children.Add(img);
                stc.Children.Add(lbl);

                stcList.Children.Add(bd);
                //cnvList.Children.Add(stc);
            }
        }
        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //System.Windows.Application.Current.MainWindow = this;
            btnBackward.IsEnabled = false;
            btnPrevouis.IsEnabled = false;
            btnForward.IsEnabled = false;
            btnNext.IsEnabled = false;
            btnStop.IsEnabled = false;
            btnPlay.IsEnabled = false;
            //imgBtnRepeat.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.repeat.Non.png"));
            this.Topmost = (Properties.Settings.Default.IsTopMost) ? true : false;
            sldVolume.Value = Convert.ToDouble(Properties.Settings.Default.volum);
            player.Volume = Convert.ToDouble(sldVolume.Value / 100);
            lblVolume.Content = Convert.ToInt32(sldVolume.Value) + " %";
            tmrPosition.Interval = new TimeSpan(0, 0, 1);
            tmrPosition.Tick += tmrPosition_Tick;
            bool isEnableBorder = Properties.Settings.Default.IsEnableBorder;
            if (isEnableBorder)
            {
                this.EnableDWMDropShadow = false;
            }
            else
            {
                this.EnableDWMDropShadow = true;
            }

            string repeat_str = Properties.Settings.Default.Repeat_String;
            switch (repeat_str)
            {
                case "non":
                    repeat = EnumMediaRepeat.Non;
                    imgBtnRepeat.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.repeat.Non.png"));
                    break;
                case "one":
                    repeat = EnumMediaRepeat.One;
                    imgBtnRepeat.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.repeat.one.png"));
                    break;
                case "all":
                    repeat = EnumMediaRepeat.All;
                    imgBtnRepeat.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.repeat.All.png"));
                    break;
            }

            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                foreach (string arg in args)
                {
                    if (supportedFormat.Contains(System.IO.Path.GetExtension(arg)))
                    {
                        this.files.Add(arg);

                    }
                }
                this.isJustRun = false;
                btnPlay.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
            }

        }

        void tmrPosition_Tick(object sender, EventArgs e)
        {
            if (isPlaying)
            {
                if (isPositionChanged)
                {
                    player.Position = TimeSpan.FromSeconds(sldPlayerTime.Value);
                    isPositionChanged = false;
                }
                sldPlayerTime.Value = player.Position.TotalSeconds;
            }
        }

        EnumMediaRepeat repeat = EnumMediaRepeat.Non;
        private void player_MediaEnded(object sender, RoutedEventArgs e)
        {
            this.isPlaying = false;
            tmrPosition.IsEnabled = false;
            if (repeat == EnumMediaRepeat.One)
            {

                btnPlay.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
            }
            else if (repeat == EnumMediaRepeat.All)
            {
                btnNext.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
            }
        }

        private void player_MediaOpened(object sender, RoutedEventArgs e)
        {
            this.isPlaying = true;

            sldPlayerTime.Maximum = player.NaturalDuration.TimeSpan.TotalSeconds;
            //sldPlayerTime
            tmrPosition.IsEnabled = true;
            /*
            SizeHelper sh = new SizeHelper(this.player.NaturalVideoWidth, this.player.NaturalVideoHeight);
            if (!sh.IsMax)
            {
                this.Width = sh.X;
                this.Height = sh.Y;
            }
            else
            {
                this.WindowState = WindowState.Maximized;
            }
            */
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            player.Stop();
            player.Source = null;
            this.isPlaying = false;
            tmrPosition.IsEnabled = false;
            imgBtnPlay.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.control.png"));
            btnBackward.IsEnabled = false;
            btnPrevouis.IsEnabled = false;
            btnForward.IsEnabled = false;
            btnNext.IsEnabled = false;
            btnStop.IsEnabled = false;

            stcList_Back.Visibility = System.Windows.Visibility.Hidden;
            sldVolume.Visibility = System.Windows.Visibility.Hidden;
            lblVolume.Visibility = System.Windows.Visibility.Hidden;
            stcPlayerPosition.Visibility = System.Windows.Visibility.Hidden;
            stcright.Visibility = System.Windows.Visibility.Hidden;
        }

        int fileIndex;
        private void btnPrevouis_Click(object sender, RoutedEventArgs e)
        {
            if (this.files.Count <= 0)
            {
                return;
            }
            if (fileIndex > 0)
            {
                player.Stop();
                tmrPosition.IsEnabled = false;
                player.Source = null;
                player.Source = new Uri(this.files[--fileIndex]);
                player.Play();

            }
            else if (fileIndex == 0)
            {
                player.Stop();
                tmrPosition.IsEnabled = false;
                player.Source = null;
                fileIndex = this.files.Count - 1;
                player.Source = new Uri(this.files[fileIndex]);
                player.Play();

            }
            /*

            if (this.files.Count > 0 && !rev)
            {
                this.files.Reverse();
                rev = true;
                this.fileIndex = this.files.Count - this.fileIndex - 1;
                this.fileIndex = (this.fileIndex + 1) % this.files.Count;
                player.Stop();
                tmrPosition.IsEnabled = false;
                player.Source = null;
                player.Source = new Uri(this.files[fileIndex]);
                player.Play();
            }*/
        }
        //bool rev;
        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            if (this.files.Count > 0)
            {
                //if (rev) this.files.Reverse();
                this.fileIndex = (this.fileIndex + 1) % this.files.Count;
                player.Stop();
                tmrPosition.IsEnabled = false;
                player.Source = null;
                player.Source = new Uri(this.files[fileIndex]);
                player.Play();
            }
        }

        private void player_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.GetPosition(player).X > this.ActualWidth - 100)
            {
                stcright.Visibility = System.Windows.Visibility.Visible;
                sldVolume.Visibility = System.Windows.Visibility.Visible;
                sldVolume.Height = this.ActualHeight - 200;
                lblVolume.Visibility = System.Windows.Visibility.Visible;
            }
            else if (e.GetPosition(player).Y > this.ActualHeight - 100)
            {
                stcPlayerPosition.Visibility = System.Windows.Visibility.Visible;
                sldPlayerTime.Width = this.ActualWidth - 200;
            }
            else if (e.GetPosition(player).X < 60 && e.GetPosition(player).Y < 60)
            {
                stcList_Back.Height = stcList_Back.MaxHeight = this.ActualHeight - 184;
                //SolidColorBrush sld = ((SolidColorBrush)System.Windows.Application.Current.Resources["AccentColorBrush"]);
                //stcList_Back.Background = sld;
                scrList.Height = this.ActualHeight - 230;
                stcList_Back.Visibility = System.Windows.Visibility.Visible;

                stcList_Back.MaxHeight = this.ActualHeight - 184;
                this.GeneratList();
            }
            else
            {

                stcList_Back.Visibility = System.Windows.Visibility.Hidden;
                sldVolume.Visibility = System.Windows.Visibility.Hidden;
                lblVolume.Visibility = System.Windows.Visibility.Hidden;
                stcPlayerPosition.Visibility = System.Windows.Visibility.Hidden;
                stcright.Visibility = System.Windows.Visibility.Hidden;
            }
            //this.Title = e.GetPosition(player).Y.ToString();
        }

        private void sldVolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            player.Volume = Convert.ToDouble(sldVolume.Value / 100);
            lblVolume.Content = Convert.ToInt32(sldVolume.Value) + " %";
        }

        private void player_Loaded(object sender, RoutedEventArgs e)
        {
            sldVolume.Value = player.Volume * 100;
        }

        private void btnRepeat_Click(object sender, RoutedEventArgs e)
        {
            if (repeat == EnumMediaRepeat.Non)
            {
                repeat = EnumMediaRepeat.One;
                Properties.Settings.Default.Repeat_String = "one";
                imgBtnRepeat.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.repeat.one.png"));
            }
            else if (repeat == EnumMediaRepeat.One)
            {
                repeat = EnumMediaRepeat.All;
                Properties.Settings.Default.Repeat_String = "all";
                imgBtnRepeat.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.repeat.All.png"));
            }
            else if (repeat == EnumMediaRepeat.All)
            {
                repeat = EnumMediaRepeat.Non;
                Properties.Settings.Default.Repeat_String = "non";
                imgBtnRepeat.Source = new BitmapImage(new Uri("pack://application:,,,/R/appbar.repeat.Non.png"));
            }
            Properties.Settings.Default.Save();
        }
        //double firstPosition;

        private void btnPreperence_Click(object sender, RoutedEventArgs e)
        {
            Window_Preference wind = new Window_Preference();
            wind.ShowDialog();
        }

        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            Window_About frm = new Window_About();
            frm.ShowDialog();
        }

        private void sldVolume_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            sldVolume.Value += (double)e.Delta / 100;
        }

        bool isPositionChanged;

        private void sldPlayerTime_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            tmrPosition.IsEnabled = false;
        }

        private void sldPlayerTime_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isPositionChanged = true;
            tmrPosition.IsEnabled = true;
        }

        private void sldPlayerTime_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
            {
                player.Position += TimeSpan.FromSeconds(5);
                sldPlayerTime.Value = player.Position.TotalSeconds;
            }
            else
            {
                player.Position -= TimeSpan.FromSeconds(5);
                sldPlayerTime.Value = player.Position.TotalSeconds;
            }
            //
        }

        bool isJustRun = true;
        private void MetroWindow_Drop(object sender, System.Windows.DragEventArgs e)
        {
            try
            {
                //fileIndex = this.files.Count;
                var dropedFiles = (string[])e.Data.GetData(System.Windows.Forms.DataFormats.FileDrop);
                foreach (string dr in dropedFiles)
                {
                    string x = System.IO.Path.GetExtension(dr);
                    if (supportedFormat.Contains(System.IO.Path.GetExtension(dr)))
                    {
                        if (!files.Contains(dr))
                        {
                            files.Add(dr);
                        }
                    }
                }
                if (isJustRun)
                {
                    btnPlay.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
                    isJustRun = false;
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        private void player_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount > 1)
            {
                /*
                 * if (this.WindowState == System.Windows.WindowState.Minimized)
                {
                    this.WindowState = System.Windows.WindowState.Maximized;
                }
                else
                 */
                if (this.WindowState == System.Windows.WindowState.Maximized)
                {
                    this.WindowState = System.Windows.WindowState.Normal;
                }
                else if (this.WindowState == System.Windows.WindowState.Normal)
                {
                    this.WindowState = System.Windows.WindowState.Maximized;
                }
            }
            //System.Windows.Forms.MessageBox.Show(this.player.NaturalVideoWidth.ToString() + "\t" + this.ActualWidth.ToString() + "\t" + this.player.ActualWidth.ToString());
            //System.Windows.Forms.MessageBox.Show(this.player.NaturalVideoHeight.ToString() + "\t" + this.ActualHeight.ToString() + "\t" + this.player.ActualHeight.ToString());
        }

        private void btnClearAll_Click(object sender, RoutedEventArgs e)
        {
            player.Stop();
            player.Source = null;
            this.isPlaying = false;
            tmrPosition.IsEnabled = false;
            this.files = new List<string>();
            fileIndex = 0;
            stcList.Children.Clear();
            stcList_Back.Visibility = System.Windows.Visibility.Hidden;
            btnBackward.IsEnabled = false;
            btnPrevouis.IsEnabled = false;
            btnForward.IsEnabled = false;
            btnNext.IsEnabled = false;
            btnStop.IsEnabled = false;
            btnPlay.IsEnabled = false;
        }

        private void btnBackward_Click(object sender, RoutedEventArgs e)
        {
            player.Position -= TimeSpan.FromSeconds(5);
            sldPlayerTime.Value = player.Position.TotalSeconds;
        }

        private void btnForward_Click(object sender, RoutedEventArgs e)
        {
            player.Position += TimeSpan.FromSeconds(5);
            sldPlayerTime.Value = player.Position.TotalSeconds;
        }

    }
    public enum EnumMediaRepeat { Non = 0, One = 1, All = 2 }
}